﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight.Command;
using Northwind.Model;
using Northwind.Application;

namespace Northwind.ViewModel
{
    public class MainWindowViewModel
    {
        private readonly IUIDataProvider _dataProvider;
        private readonly IToolManager _toolManager;

        private RelayCommand _showDetailsCommand;
        public RelayCommand ShowDetailsCommand
        {
            get
            {
                return _showDetailsCommand ??
                       (_showDetailsCommand =
                        new RelayCommand(
                            ShowCustomerDetails,
                            IsCustomerSelected));
            }
        }

        private string _selectedCustomerID;
        public string SelectedCustomerID
        {
            get { return _selectedCustomerID; }
            set
            {
                _selectedCustomerID = value;
                ShowDetailsCommand.RaiseCanExecuteChanged();
            }
        }

        private IList<Customer> _customers;
        public IList<Customer> Customers
        {
            get
            {
                if (_customers == null)
                {
                    GetCustomers();
                }
                return _customers;
            }
        }

        public ObservableCollection<ToolViewModel> Tools 
            { get { return _toolManager.Tools; } }

        public MainWindowViewModel(
            IUIDataProvider dataProvider,
            IToolManager toolManager)
        {
            _dataProvider = dataProvider;
            _toolManager = toolManager;
        }

        public void ShowCustomerDetails()
        {
            if (!IsCustomerSelected())
                throw new InvalidOperationException(
                    "Unable to show customer because no "
                    + "customer is selected.");

            _toolManager.OpenCustomerDetails(SelectedCustomerID);
        }

        public bool IsCustomerSelected()
        {
            return !string.IsNullOrEmpty(SelectedCustomerID);
        }

        private void GetCustomers()
        {
            _customers =
                _dataProvider.GetCustomers();
        }
    }
}